package com.java2104.controller;

import com.java2104.entity.User;
import com.java2104.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 完成跳转登录页面和处理登录表单提交
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public String login(String loginname, String password, HttpSession session){
        User user = userService.login(loginname,password);
        if(user!=null){
            session.setAttribute("loginUser",user);
            return "success";
        }else {
            return "fail";
        }
    }
    @GetMapping("/login")
    public String login(){
        return "loginForm";
    }
    //系统主界面
    @GetMapping("/main")
    public String main(@SessionAttribute(name = "loginUser",required = false) User loginUser){
        if(loginUser==null || loginUser.getLoginname()==null){
            return "redirect:/login";
        }
        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();//销毁会话，使其过期；会话中保存的登录状态也随之消失
        return "redirect:/login";
    }
}
